using System;
using Microsoft.SharePoint;

namespace SharePoint.DataMapper
{
	/// <summary>
	/// ListContext class.
	/// </summary>
	public class ListContext : WebContext
	{
		private readonly string _listNameIdUrl;
		private SPList _list;

		/// <summary>
		/// Initializes a new instance of the <see cref="ListContext"/> class.
		/// </summary>
		/// <param name="listUrl">Absolute URL of the List</param>
		public ListContext(string listUrl)
			: base(listUrl)
		{
			if (Web != null)
			{
				_listNameIdUrl = listUrl.Remove(0, Web.Url.Length);
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ListContext"/> class.
		/// </summary>
		/// <param name="webUrlOrId">The web URL or id.</param>
		/// <param name="listNameOrId">The list name or id.</param>
		public ListContext(string webUrlOrId, string listNameOrId) : base(webUrlOrId)
		{
			_listNameIdUrl = listNameOrId;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ListContext"/> class.
		/// </summary>
		/// <param name="siteId">The site id.</param>
		/// <param name="webId">The web id.</param>
		/// <param name="listNameOrId">The list name or id.</param>
		public ListContext(Guid siteId, Guid webId, string listNameOrId) : base(siteId, webId)
		{
			_listNameIdUrl = listNameOrId;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ListContext"/> class.
		/// </summary>
		/// <param name="site">The site.</param>
		/// <param name="web">The web.</param>
		/// <param name="listNameOrId">The list name or id.</param>
		public ListContext(SPSite site, SPWeb web, string listNameOrId)
			: base(site, web)
		{
			_listNameIdUrl = listNameOrId;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ListContext"/> class.
		/// </summary>
		/// <param name="webContext">The web context.</param>
		/// <param name="listNameOrId">The list name or id.</param>
		public ListContext(WebContext webContext, string listNameOrId)
			: base(webContext)
		{
			_listNameIdUrl = listNameOrId;
		}

		/// <summary>
		/// Gets the list.
		/// </summary>
		/// <value>The list.</value>
		public SPList List
		{
			get
			{
				if (_list == null)
				{
					_list = Service.GetList(Web, _listNameIdUrl);
				}
				return _list;
			}
		}
	}
}